package demo;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibMysqlSessionFactory;
import util.HibOracleSessionFactory;
import bean.RaProcess;
import bean.User;

public class BaseDemo {
	static Logger logger = Logger.getLogger(BaseDemo.class);

	public static void main(String[] args) {
		User user1 = saveTest();
		queryTest();
		logger.info("-------");
		User user2 = saveTest();
		queryTest();
		logger.info("-------");
		updateTest(user1);
		queryTest();
		logger.info("-------");
		deleteTest(user2);
		queryTest();
		logger.info("-------");
		queryOracleTest();
	}

	private static List<RaProcess> queryOracleTest() {
		Session session = HibOracleSessionFactory.getSession();
		try {
			Query query = session.createQuery("from RaProcess where 1 = :flag");
			query.setParameter("flag", 1);
			query.setFirstResult(0);
			query.setMaxResults(5);
			@SuppressWarnings("unchecked")
			List<RaProcess> result = query.list();
			logger.debug(result);
			return result;
		} finally {
			HibOracleSessionFactory.closeSession();
		}
	}

	public static User saveTest() {
		Session session = HibMysqlSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			User user = new User();
			user.setAge(10);
			user.setName("test");
			session.saveOrUpdate(user);
			tx.commit();
			return user;
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			throw new RuntimeException(e);
		} finally {
			HibMysqlSessionFactory.closeSession();
		}
	}

	public static void queryTest() {
		Session session = HibMysqlSessionFactory.getSession();
		try {
			// User user1 = (User) session.get(User.class, 1L);
			// logger.info(user1);
			Query query = session.createQuery("from User where 1 = :flag");
			query.setParameter("flag", 1);
			@SuppressWarnings("unchecked")
			List<User> users = query.list();
			logger.info(users);
		} finally {
			HibMysqlSessionFactory.closeSession();
		}
	}

	public static void updateTest(User user) {
		Session session = HibMysqlSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			user.setAge(1000);
			logger.info("++user insert:" + user);
			session.saveOrUpdate(user);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			throw new RuntimeException(e);
		} finally {
			HibMysqlSessionFactory.closeSession();
		}
	}

	public static void deleteTest(User user) {
		Session session = HibMysqlSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.delete(user);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			throw new RuntimeException(e);
		} finally {
			HibMysqlSessionFactory.closeSession();
		}
	}
}
